#include "server_base.h"
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <random>
#include <sstream>
#include <iomanip>

using grpc::ServerBuilder;

// 生成服务端唯一ID（基于时间戳+随机数）
static std::string GenerateServerId() {
  auto now = std::chrono::system_clock::now();
  auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
                       now.time_since_epoch())
                       .count();

  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<> dis(1000, 9999);

  std::stringstream ss;
  ss << "device-" << timestamp << "-" << dis(gen);
  return ss.str();
}

// 获取当前时间戳（ISO格式）
static std::string GetCurrentTimestamp() {
  auto now = std::chrono::system_clock::now();
  auto in_time_t = std::chrono::system_clock::to_time_t(now);

  std::stringstream ss;
  ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %H:%M:%S");
  return ss.str();
}

ServerBase::ServerBase() : serverId_(GenerateServerId()) {
  std::cout << "[ServerBase] Server ID generated: " << serverId_ << std::endl;
}

ServerBase::~ServerBase() { StopServer(); }

bool ServerBase::StartServer(const std::string &port) {
  std::lock_guard<std::mutex> lock(serverMutex_);

  if (isRunning_) {
    std::cout << "[ServerBase] Server is already running" << std::endl;
    return false;
  }

  // 启动服务端线程
  std::string address = "0.0.0.0:" + port;
  serverThread_ = std::thread(&ServerBase::RunServer, this, address);
  isRunning_ = true;

  std::cout << "[ServerBase] Server started on " << address
            << " (thread: " << serverThread_.get_id() << ")" << std::endl;
  return true;
}

void ServerBase::StopServer() {
  std::lock_guard<std::mutex> lock(serverMutex_);

  if (!isRunning_)
    return;

  // 停止gRPC服务
  if (server_) {
    server_->Shutdown();
    std::cout << "[ServerBase] Server shutdown initiated" << std::endl;
  }

  // 等待线程结束
  if (serverThread_.joinable()) {
    serverThread_.join();
    std::cout << "[ServerBase] Server thread exited" << std::endl;
  }

  isRunning_ = false;
  server_.reset();
  std::cout << "[ServerBase] Server stopped completely" << std::endl;
}

bool ServerBase::IsServerRunning() const {
  std::lock_guard<std::mutex> lock(serverMutex_);
  return isRunning_;
}

void ServerBase::RunServer(const std::string &address) {
  ServerBuilder builder;

  // 绑定地址（不使用TLS，适合局域网通信）
  builder.AddListeningPort(address, grpc::InsecureServerCredentials());

  // 注册服务实现
  builder.RegisterService(this);

  // 构建服务端
  server_ = builder.BuildAndStart();

  if (!server_) {
    std::cerr << "[ServerBase] Failed to build server on " << address
              << std::endl;
    return;
  }

  // 阻塞等待服务结束
  server_->Wait();
}

GRPCStatus ServerBase::Ping(GRPCServerContext *context,
                            const PingRequest *request,
                            PongResponse *response) {
  std::cout << "[ServerBase] Ping received from client: "
            << request->client_id() << " (timestamp: " << request->timestamp()
            << ")" << std::endl;

  // 构造响应
  response->set_success(true);
  response->set_server_id(serverId_);
  response->set_timestamp(GetCurrentTimestamp());
  response->set_message("Ping received successfully");

  return GRPCStatus::OK;
}

GRPCStatus ServerBase::GetDeviceInfo(GRPCServerContext *context,
                                     const DeviceInfoRequest *request,
                                     DeviceInfoResponse *response) {
  std::string platform, deviceModel, systemVersion;
  GetPlatformInfo(platform, deviceModel, systemVersion);

  response->set_platform(platform);
  response->set_device_model(deviceModel);
  response->set_system_version(systemVersion);

  std::cout << "[ServerBase] Device info requested: " << platform << " / "
            << deviceModel << " / " << systemVersion << std::endl;

  return GRPCStatus::OK;
}
